/*====================================================================
Filename:	video.js
Author: 	Didi Alamsaputra
Date: 		7/23/2009
Purpose: 	Main module for JI Media JS/ajax utilities
=======================================================================*/


/* ================
	INITIALIZATION
   ================*/
flwMediaAjaxPath = "/flwMedia/ajax.cfm"; 	// The main ajax file 
currentVideoId = 0;							// The video id that is playing
nVideoChannel = 0;							// The number of video channel 
aVideoChannelId = new Array();				// The array for the video channel ID
aChannelCallsign = new Array(); 			// The array for the video channels available
aChannelName = new Array();		 			// The array for the video channels available
aVideoId = new Array()						// The array for the video id
aVideoChannelCallsign = new Array(); 		// The array for the video channel
aVideoChannelName = new Array(); 			// The array for the video channel
aVisibility = new Array(); 					// The array for the video channel visibility
aVideoFile = new Array();					// The array for the video files
aVideoHDFile = new Array();					// The array for the high definition video 
aVideoTitle = new Array();					// The array for the video titles
aVideoDescription = new Array();			// The array for the video description
aVideoDuration = new Array();				// The array for the video duration
aVideoThumbnail = new Array();				// The array for the video thumbnails
aVideoSplash = new Array();					// The array for the video splash images
aVideoStreamingPath = new Array();			// The array for the video path akamai streaming
aVideoAdStreamingPath = new Array();		// The array for the video ads
aVideoSubscriptionTypeId = new Array();		// The array if the video has a restriction
aVideoMessageText = new Array();	// The array if the video has restriction text to show to the user
aVideoAdId = new Array();					// The array for the video ad ids  
aVideoPath_Original = new Array()		// The array for location of the source file if the allow download is true
currentVideoAdIndex = 0;					// The current video ad index
nVideoChannel = 1;
videoThumbnailId = "";
divCommentId = "";
videoLinkid = "";
originalvideoTitle = ''; 
originalvideoDescription = ''
clip = "";		// The clip variable that is used for flowplayer
playlist = "";
addthis_share = {url:""};					// This variable is used for the "share this" button for sharing the video on different sites
googleTrackingID = "";
gaPlugin = "";
showAd = 0;									// We want to show ad the first time someone watch a video
videoAdCount = 0;


if (!isDefined("highQualityFlag")){
	highQualityFlag = false;
}
if (!isDefined("subscriptionTypeId")){
	subscriptionTypeId = 0;
}

sProviderURL = "rtmp://flwoutdoor.fcod.llnwd.net/a479/e1/";
//We are hardcoding these video ads for now. At some point we need to change this

//aVideoAdId[0] = 2439;
aVideoAdId[0] = 3732;
aVideoAdId[1] = 2438;

//aVideoAdStreamingPath[0] = "mp4:/0/2/PTSI_Preroll_2009.mp4";
aVideoAdStreamingPath[0] = "mp4:/0/4/VTS_01_1.mp4";
aVideoAdStreamingPath[1] = "mp4:/0/2/MinnKota_Fortrex.mp4";
videoAdTimer = "";								// This is the timer for the video advertisement

//Assign the google tracking ID based on the domain
if (location.hostname.search(/dev/i)>=0){
	googleTrackingID = "UA-10911906-3";
	environment = "dev"; // This is for tracking purposes, we want to use dev.services.jacobsinteractive.com
	provider = "jidocs";
	
}else if (location.hostname.search(/test/i)>=0){
	googleTrackingID = "UA-10911906-4";
	environment = "test";
	provider = "jidocs";
}else if (location.hostname.search(/collegefishing/i)>=0 ){
	googleTrackingID = "UA-1178649-9";
	environment = "www";	// For tracking, in production we want to use services.jacobsinteractive.com
	provider = "akamai";
}else{
	googleTrackingID = "UA-1178649-8";
	environment = "www";	// For tracking, in production we want to use services.jacobsinteractive.com
	provider = "akamai";
}

//General purpose function to check if a certain variable is defined
function isDefined( variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}



/* =========================================
	FUNCTIONS FOR GETTING THE CHANNEL VIDEOS 
   =========================================*/
// getting the videos in certain channel using ajax
function getVideosInChannel(callsign,index) {
	$.post(flwMediaAjaxPath, {
			method:				"getVideosInChannel"
			,callsign:		callsign
		}, function(response) {
			
			populateVideos(response,callsign,index,"getVideosInChannel");
	});	
}
function getVideosInChannelMaxResults(callsign,index,maxResults) {
	$.post(flwMediaAjaxPath, {
			method:				"getVideosInChannel"
			,callsign:		callsign
			,maxResults:	maxResults
		}, function(response) {
			
			populateVideos(response,callsign,index,"getVideosInChannel");
	});	
}

function getVideosInChannelTournament(callsign,tournamentId){
	
	$.post(flwMediaAjaxPath, {
			method:				"getVideosInChannel"
			,callsign:		callsign
			,tournamentId: 	tournamentId
		}, function(response) {
			populateVideos(response,callsign,tournamentId,"getVideosInChannel");
	});	
}

function getVideosInChannelTournamentMember(callsign,tournamentId,memberId){
	
	$.post(flwMediaAjaxPath, {
			method:				"getVideosInChannel"
			,callsign:		callsign
			,tournamentId: 	tournamentId
			,memberId: memberId
		}, function(response) {
			populateVideos(response,callsign,tournamentId,"getVideosInChannel");
		}
	);	
}
// populating the videos from the ajax response
function populateVideos(response,callsign, index,method){
	
	var strTemp = '(' + response + ')';
	var json = eval(strTemp);
	var counterMax = 0;
	var arrayLength = 0;
	var currentURL = location.pathname;
	
	if (currentURL.search(/flwondemand.cfm/i)>0){ 
		showAd = 1;	 // every time we populate videos we want to play the ad video
		currentVideoAdIndex = Math.floor(Math.random()*2);
		
	}
	
	if (json.BERROR){
		if (callsign == 'collegefishingwebsite'){
			getVideosInChannel('collegefishingwebsite',1);
		}else{
			alert(json.SERROR);
		}
	}else{
		
		if (method == "searchMediaItems"){
			arrayLength = populateSearchItems(json,index);
		}else{
			arrayLength = populateChannelItems(json,index);
		}
		
		if (arrayLength > 0){
		
			buildChannelVideos(arrayLength,aVideoChannelCallsign[index]);
			if (document.getElementById("player")){
				instantiateVideoPlayer(currentVideoId);
				if (highQualityFlag) {
					if (highQualityFlag == true){
						loadHDVideo(currentVideoId, 0);
					}
				}else{
					
					loadVideo(currentVideoId, 0);
				}
			}
		}else{
			showNoVideosFound();
		}
	}
}

function populateSearchItems(json,index){
	var arrayLength = 0;
	aChannelName[index] = "Search";
	arrayLength = json.AFILE.length;
	
	for (var counter = 0;counter<arrayLength;counter++){	
		aVideoChannelId[counter] = 0; 
		aVideoChannelCallsign[counter] = "Search";
		aVideoChannelName[counter] = "Search";
		aVideoId[counter]= json.AFILE[counter].ID;
		aVideoTitle[counter]= json.AFILE[counter].TITLE;
		aVideoDescription[counter] = json.AFILE[counter].DESCRIPTION;
		aVideoDuration[counter] = json.AFILE[counter].DURATION;
		aVideoFile[counter] = json.AFILE[counter].PATH;
		aVideoThumbnail[counter] = json.AFILE[counter].THUMBNAIL; 
		if  (environment == "www" ){
			aVideoStreamingPath[counter] = json.AFILE[counter].STREAMING_PATH.slice(sProviderURL.length);
		}else{
			aVideoStreamingPath[counter] = json.AFILE[counter].STREAMING_PATH;
		}
		aVideoHDFile[counter] = '';
		
		if  (json.AFILE[counter].SUBSCRIPTIONTYPEID != ""){
			aVideoSubscriptionTypeId[counter]  = json.AFILE[counter].SUBSCRIPTIONTYPEID; 
		}else{
			aVideoSubscriptionTypeId[counter]  = 0;
		}
		
		aVideoMessageText[counter]  = json.AFILE[counter].MESSAGETEXT;
		aVideoPath_Original[counter] = json.AFILE[counter].PATH_ORIGINAL;
	}
	return arrayLength;
}

function populateChannelItems(json,index){
	var arrayLength = 0;
	aChannelName[index] = json.CHANNEL.NAME;
	arrayLength = json.CHANNEL.AFILE.length;
	for (var counter = 0;counter<arrayLength;counter++){
		aVideoChannelCallsign[counter] = json.CHANNEL.CALLSIGN;
		aVideoChannelName[counter] = json.CHANNEL.NAME;
		aVideoChannelId[counter] = json.CHANNEL.AFILE[counter].CHANNELID; 
		aVideoId[counter]= json.CHANNEL.AFILE[counter].ID;
		aVideoTitle[counter]= json.CHANNEL.AFILE[counter].TITLE;
		aVideoDescription[counter] = json.CHANNEL.AFILE[counter].DESCRIPTION;
		aVideoDuration[counter] = json.CHANNEL.AFILE[counter].DURATION;
		aVideoFile[counter] = json.CHANNEL.AFILE[counter].PATH;
		aVideoThumbnail[counter] = json.CHANNEL.AFILE[counter].THUMBNAIL; 
		if  (environment == "www"){
			aVideoStreamingPath[counter] = json.CHANNEL.AFILE[counter].STREAMING_PATH.slice(sProviderURL.length);
		}else{
			aVideoStreamingPath[counter] = json.CHANNEL.AFILE[counter].STREAMING_PATH;
		}
		aVideoHDFile[counter] = json.CHANNEL.AFILE[counter].FILENAME_HD;
		if  (json.CHANNEL.AFILE[counter].SUBSCRIPTIONTYPEID != ""){
			aVideoSubscriptionTypeId[counter]  = json.CHANNEL.AFILE[counter].SUBSCRIPTIONTYPEID; 
		}else{
			aVideoSubscriptionTypeId[counter]  = 0;
		}
		
		aVideoMessageText[counter]  = json.CHANNEL.AFILE[counter].MESSAGETEXT;
	}
	return arrayLength;
}

/* ===================================================
	FUNCTIONS FOR SEARCHING VIDEOS IN CERTAIN CHANNELS
   ===================================================*/
function searchMediaItems(callsigns,searchKeywords,maxresults){
	$.post(flwMediaAjaxPath, {
			method:			"searchMediaItems"
			,callsigns:		callsigns
			,searchKeywords:searchKeywords
			,maxResults:	maxresults
		}, function(response) {
			populateVideos(response,callsigns,0,"searchMediaItems");
			
	});	
}

function searchMediaItemsTournamentMember(callsigns,searchKeywords,maxresults,tournamentId,memberId){
	
	$.post(flwMediaAjaxPath, {
			method:			"searchMediaItems"
			,callsigns:		callsigns
			,searchKeywords:searchKeywords
			,maxResults:	maxresults
			,tournamentId:  tournamentId
			,memberId:		memberId
		}, function(response) {
			
			populateVideos(response,callsigns,0,"searchMediaItems");
			
	});	
}


/* ===================================================
	FUNCTIONS FOR INSTANTIATING FLOW PLAYER
   ===================================================*/
// Load the flow player with the rtmp plugin for akamai
function instantiateVideoPlayer(vid){
	var sFlowPlayerKey = "#@e71060de35bb83f125e";
	var hostURL = "http://" + location.hostname;
	var flowplayerURL = "";
	var currentURL = location.pathname;
	var playlist = "";
	// The opacity of the top info bar for advertisement
	

	if (showAd == 1 ){ 
		playlist = [{'url':aVideoThumbnail[vid], 'autoPlay':true,'scaling': 'fit'},{'url':aVideoAdStreamingPath[currentVideoAdIndex], 'autoPlay':false,'provider':'akamai','scaling': 'fit'},{'url':aVideoStreamingPath[vid], 'autoplay':true,'provider':provider,'scaling': 'fit'}];
	}else{
		if (aVideoSubscriptionTypeId[currentVideoId] != 0 && aVideoSubscriptionTypeId[currentVideoId] != subscriptionTypeId){
			playlist = [{'url':aVideoThumbnail[currentVideoId], 'autoPlay':true,'scaling': 'fit'}];
		}else{
			
			playlist = [{'url':aVideoThumbnail[vid], 'autoPlay':true,'scaling': 'fit'},{'url':aVideoStreamingPath[vid], 'autoPlay':false,'provider':provider,'scaling': 'fit'}];
		}
	}
	if (hostURL.search(/fantasyfishing/i)>0 ){
		sFlowPlayerKey = "#@3144ab9792f8c7b1a5e";
	}
	
	if (hostURL.search(/collegefishing/i)>0 ){ 	
		setUpCollegeFishingPlayer(hostURL, sFlowPlayerKey, playlist);
	}else{
		setUpFLWOutdoorsPlayer(hostURL, sFlowPlayerKey, playlist);
		
	}
	
}	


//Function to set up the college fishing player
function setUpCollegeFishingPlayer(hostURL, sFlowPlayerKey, playlist){
	flowplayerURL = hostURL.replace("collegefishing","flwoutdoors") + "/FLWMedia/CFVideoPlayer.swf";
	sFlowPlayerKey = '#@8a338f8ca2746794047';

	flowplayer("player", flowplayerURL,
		{	
			key:sFlowPlayerKey,
			playlist: playlist,
			play: { 
				width: 60, 
				height: 60 
			},
			plugins: {
				gatracker: {
					videoid:aVideoId[currentVideoId],
					env:environment,
					areaid:mediaItemAreaId,
					mediachannelid:aVideoChannelId[currentVideoId],
					google_id:googleTrackingID,
					debug:false
				},
				 jidocs: { 
					url: 'flowplayer.pseudostreaming-3.1.3.swf' 
				},
				content: { 
					backgroundColor: '#000000'
				}
	
			}
			
		}   
	);
	loadEvents();
}

//Function to setup the FLW Outdoors player
function setUpFLWOutdoorsPlayer(hostURL, sFlowPlayerKey, playlist){
	var adZIndex = 0;
	var adInfoOpacity = 0;
	
	if (showAd == 1){
		adInfoOpacity = 0.9;
		adZIndex = 20; // to put it on the top of everything
	}
	if (location.pathname == '/forrest-wood-cup/2010/Video.cfm'){
		flowplayer("player", {src:hostURL.replace("fantasyfishing","flwoutdoors") + "/FLWMedia/FLWVideoPlayer.swf"},
		{	
			key:sFlowPlayerKey,
			playlist: playlist,
			play: { 
				width: 90, 
				height: 90 
			},
			
			canvas :{
				backgroundColor: '#000000'
			},
			plugins: {
				controls: {
					'autoHide':true,
					'hideDelay': 3000
				},
				gatracker: {
					videoid: aVideoId[currentVideoId],
					env 	: environment,
					areaid: mediaItemAreaId,
					mediachannelid: aVideoChannelId[currentVideoId],
					google_id: googleTrackingID,
					debug:false
				},
				 jidocs: { 
					url: 'flowplayer.pseudostreaming-3.1.3.swf' 
				},
				messageContent:{
					url:'contentPlugin.swf',
					backgroundColor: '#393939',
					backgroundGradient:[0, 0],
					border: '0px',
					borderRadius: 0,
					top:0,
					zIndex: 30,
					width:480,
					height: 25,
					opacity :0
				}
	
			}
		}   
	);}
	else{
	flowplayer("player", {src:hostURL.replace("fantasyfishing","flwoutdoors") + "/FLWMedia/FLWVideoPlayer.swf",wmode: 'opaque'},
		{	
			key:sFlowPlayerKey,
			playlist: playlist,
			play: { 
				width: 90, 
				height: 90 
			},
			
			canvas :{
				backgroundColor: '#000000'
			},
			logo:{
				bottom: 35,
				right: 10
			},
			plugins: {
				controls: {
					'autoHide':true,
					'hideDelay': 3000
				},
				gatracker: {
					videoid: aVideoId[currentVideoId],
					env 	: environment,
					areaid: mediaItemAreaId,
					mediachannelid: aVideoChannelId[currentVideoId],
					google_id: googleTrackingID,
					debug:false
				},
				 jidocs: { 
					url: 'flowplayer.pseudostreaming-3.1.3.swf' 
				},
				messageContent:{
					url:'contentPlugin.swf',
					backgroundColor: '#393939',
					backgroundGradient:[0, 0],
					border: '0px',
					borderRadius: 0,
					top:0,
					zIndex: 30,
					width:480,
					height: 25,
					opacity :0
				}
	
			}
		}   
	);
	
	loadEvents();
	}
}


function loadEvents(){
	
	$f("player").onLoad(function() { 
		videoAdCount = 0;
		instantiateVideoPlayerStyle(); 
		
		if (aVideoSubscriptionTypeId[currentVideoId] != 0 && aVideoSubscriptionTypeId[currentVideoId] != subscriptionTypeId){
			var contentPlugin = $f("player").getPlugin("messageContent");
			if (contentPlugin) {
				contentPlugin.css({opacity:1,zIndex:30,height:'60px',width:messageContentWidth});
				contentPlugin.css({color:'#ffffff'});
				var textMessage = "<p><font size='14' >" + aVideoMessageText[currentVideoId] + "</font></p>";
				contentPlugin.setHtml(textMessage);
			}
			
			
		}
		if (showAd == 1){
			var controlPlugin = $f("player").getPlugin("controls");
			
			
		}
	}); 
	// Every time we begin to load the clip, we want to set the video id for tracking
	$f("player").onBegin(function() { 
		var gaPlugin = $f("player").getPlugin("gatracker");
		
		if (gaPlugin) 
			if (showAd == 1){
				gaPlugin.setVID(aVideoAdId[currentVideoAdIndex]);
				
			
			}else{
				gaPlugin.setVID(aVideoId[currentVideoId]);
			}
	}); 
	
	/*$f("player").onStart(
		function(clip) {
			if (videoAdCount ==1){
				var contentPlugin = $f("player").getPlugin("content");
				var remaining = clip.duration - $f("player").getTime();
				videoAdTimer= setInterval(function() {
						var remaining = clip.duration - $f("player").getTime(); 
						contentPlugin.setHtml("Advertisement: Your video will play in " + (Math.round(remaining)) + " seconds");
						if (remaining < 1) clearInterval(videoAdTimer); 
					}, 1000
				);
			}
		}
	);*/
	
	
	$f("player").onFinish(function() {
		if (showAd == 1){
			videoAdCount = videoAdCount + 1;
			if (videoAdCount ==1){
				var controlPlugin = $f("player").getPlugin("controls");
				if(controlPlugin) controlPlugin.setEnabled({scrubber: false});
			}
			if (videoAdCount > 1){
				showAd = 0;
				var controlPlugin = $f("player").getPlugin("controls");
				if(controlPlugin) controlPlugin.setEnabled({scrubber: true});
			}
		}
	});
}